<script setup>
import { ref } from "vue";
import { Plus, Picture } from "@element-plus/icons-vue";
import ExpClassSelect from "./ExpClassSelect.vue";

import {
  filerMgrUpdateStatusService,
  filerMgrAddService,
  filerMgrUpdateService,
} from "@/api";
import { useUserStore } from "@/stores";

// 使用用户存储模块
const userInfo = useUserStore();

// 抽屉的可见性状态
const visibleDrawer = ref(false);

// 默认表单数据
const defaultForm = {
  id: 0,
  name: "",
  description: "",
  imageUrl: "",
  blur: 0,
  brightness: 0,
  contrast: 0,
  noise: 0,
  saturation: 0,
  status: 0,
  createTime: "",
  updateTime: "",
};

// 表单模型，用于数据绑定和操作
const formModel = ref({ ...defaultForm });

// 表单规则
const rules = {
  // categoryId: [{ required: true, message: "请选择分类名称", trigger: "blur" }],
  name: [{ required: true, message: "请输入滤镜名称", trigger: "blur" }],
  // imageUrl: [{ required: true, message: "请上传图片", trigger: "blur" }],
  description: [{ required: true, message: "请输入描述", trigger: "blur" }],
};

// 打开抽屉函数------start
let titleDrawer = ref("编辑用户");
let operateStatus = ref("edit");
let loadingDetail = ref(false);

/**
 * 打开抽屉函数，根据传入的行数据和操作类型，决定是编辑、添加还是角色分配操作
 * @param {Object} row - 行数据
 * @param {String} operate - 操作类型
 */
const open = async (row, operate) => {
  console.log(row);
  operateStatus.value = operate;
  visibleDrawer.value = true;
  if (operate == "edit") {
    formModel.value = row;
    titleDrawer.value = "编辑滤镜";
  }
  if (operate == "add") {
    formModel.value = { ...defaultForm };
    titleDrawer.value = "添加滤镜";
  }
};
defineExpose({ open });
// 打开抽屉函数------end

// 切换用户状态-----start
// 加载状态的ref对象，用于状态切换的动画
let loadingStatus = ref(false);

/**
 * 异步函数，用于处理用户状态更改
 * @param {Object} row - 包含行数据的对象，此对象应包含状态和ID属性
 * @returns {Promise}
 */
const onStatusChange = async () => {
  try {
    loadingStatus.value = true;
    // 根据当前行的状态，重新转回1、0
    formModel.value.status = formModel.value.status == 0 ? 1 : 0;
    await filerMgrUpdateStatusService(
      formModel.value.id,
      formModel.value.status
    );
    ElMessage.success("修改成功");
  } catch (error) {
    formModel.value.status = formModel.value.status == 0 ? 1 : 0;
    ElMessage.error("修改失败");
  } finally {
    loadingStatus.value = false;
  }
};
// 切换用户状态-----end

// 添加或编辑操作-------start

let loadingAdd = ref(false); // 添加和编辑操作的加载状态
const formRef = ref(); // 表单引用，用于表单验证和提交

// 发送到父组件的成功事件
const emit = defineEmits(["success"]);

/**
 * 提交表单数据，根据是否有ID判断是进行编辑还是添加操作
 * @param {String} state - 表单状态（已发布或草稿）
 */
const onSubmit = async (state) => {
  await formRef.value.validate(); // 验证表单
  loadingAdd.value = true;
  try {
    if (operateStatus.value == "edit") {
      console.log("编辑操作");
      await filerMgrUpdateService(formModel.value);
      ElMessage.success("编辑成功");
      visibleDrawer.value = false;
      emit("success", "edit");
    }

    if (operateStatus.value == "add") {
      // 添加请求
      let res = await filerMgrAddService(formModel.value);
      console.log(res);
      ElMessage.success("添加成功");
      visibleDrawer.value = false;
      emit("success", "add");
    }
  } catch (error) {
    console.log(error);
  } finally {
    loadingAdd.value = false;
  }
};
// 添加或编辑操作-------end
const onUpdate = (data) => {
  formModel.value.imageUrl = data;
  console.log(data);
};
</script>

<template>
  <!-- 抽屉组件，用于编辑和添加用户 -->
  <el-drawer
    v-model="visibleDrawer"
    :title="titleDrawer"
    direction="rtl"
    size="60%"
    style="padding: 30px"
  >
    <!-- 表单组件，用于输入信息 -->
    <el-form
      :model="formModel"
      ref="formRef"
      :rules="rules"
      label-width="100px"
      label-position="top"
      v-loading="loadingDetail"
    >
      <!-- <el-form-item label="滤镜" prop="imageUrl">
        <Upload&Preview
          :imageUrl="formModel.imageUrl"
          @update="onUpdate"
        ></Upload&Preview>
      </el-form-item> -->
      <el-form-item label="滤镜预览" prop="imageUrl">
        <el-image
          style="width: 200px; height: 200px; border: 1px solid #eee"
          fit="cover"
          :src="formModel.imageUrl"
          :preview-src-list="[formModel.imageUrl]"
        >
          <template #error>
            <div class="image-slot">
              <el-icon><Picture /></el-icon>
              暂无
            </div>
          </template>
        </el-image>
      </el-form-item>
      <el-form-item label="滤镜名称" prop="name">
        <el-input
          v-model="formModel.name"
          placeholder="请输入滤镜名称"
        ></el-input>
      </el-form-item>
      <el-form-item label="模糊度" prop="blur">
        <el-slider v-model="formModel.blur" show-input :min="-100" :max="100" />
      </el-form-item>
      <el-form-item label="亮度" prop="brightness">
        <el-slider
          v-model="formModel.brightness"
          show-input
          :min="-100"
          :max="100"
        />
      </el-form-item>
      <el-form-item label="对比度" prop="contrast">
        <el-slider
          v-model="formModel.contrast"
          show-input
          :min="-100"
          :max="100"
        />
      </el-form-item>
      <el-form-item label="噪点" prop="noise">
        <el-slider
          v-model="formModel.noise"
          show-input
          :min="-100"
          :max="100"
        />
      </el-form-item>
      <el-form-item label="饱和度" prop="saturation">
        <el-slider
          v-model="formModel.saturation"
          show-input
          :min="-100"
          :max="100"
        />
      </el-form-item>

      <el-form-item label="描述" prop="description">
        <el-input
          v-model="formModel.description"
          placeholder="请输入描述"
        ></el-input>
      </el-form-item>

      <!-- 用户状态切换开关，仅在编辑操作时显示 -->
      <el-form-item label="状态" prop="status" v-if="operateStatus == 'edit'">
        <el-switch
          :model-value="formModel.status === 1 ? true : false"
          :loading="loadingStatus"
          @change="onStatusChange()"
        />
      </el-form-item>

      <!-- 提交表单按钮 -->
      <el-form-item>
        <el-button
          type="primary"
          :icon="Plus"
          :loading="loadingAdd"
          @click="onSubmit('已发布')"
          >提交</el-button
        >
      </el-form-item>
    </el-form>
  </el-drawer>
</template>

<style scoped lang="scss">
.avatar-uploader {
  :deep() {
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }
    .el-upload:hover {
      border-color: var(--el-color-primary);
    }
    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
    }
  }
}
.editor {
  width: 100%;
  :deep(.ql-editor) {
    min-height: 200px;
  }
}
.el-input,
.el-slider {
  max-width: 500px;
}
.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  width: 100%;
  height: 100%;
  background: var(--el-fill-color-light);
  color: var(--el-text-color-secondary);
  // font-size: 30px;
}
.image-slot .el-icon {
  font-size: 26px;
}
</style>
